package com.seaboxdata.interfaceJob;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.robin.core.base.util.StringUtils;
import com.seaboxdata.entity.Warning;
import com.seaboxdata.utils.HttpUtils;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Configuration
public class AlarmMsgSynchronizer {

    private static Gson gson = new Gson();
    @Value("${connector.daxin.vehicle.hazard.loginUrl}")
    private String loginUrl;
    @Value("${connector.daxin.vehicle.hazard.username}")
    private String username;
    @Value("${connector.daxin.vehicle.hazard.password}")
    private String password;
    @Value("${connector.daxin.vehicle.hazard.type}")
    private String type;
    @Value("${connector.daxin.vehicle.hazard.warnningUrl}")
    private String warnUrl;
    private String accessToken;

    public String doLoginRetToken() {
        try {
            String passwordInput = StringUtils.getMd5Encry(password);
            String accessToken = null;
            Map<String, String> contentMap = new HashMap<>();
            contentMap.put("username", username);
            contentMap.put("password", passwordInput.toLowerCase());
            contentMap.put("type", type);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("content-type", "application/json");

            HttpUtils.Response response = HttpUtils.doPost(loginUrl, gson.toJson(contentMap), "UTF-8", headerMap);

            if (response.getStatusCode() == 200) {
                Map<String, Object> map = gson
                        .fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {
                        }.getType());
                if (map.containsKey("message")) {
                    accessToken = map.get("message").toString();
                }
            }
            return accessToken;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public List<Warning> queryWarnningRecords() {
        if (accessToken == null) {
            accessToken = doLoginRetToken();
        }
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        headerMap.put("Authorization", accessToken);
        HttpUtils.Response response = HttpUtils.doGet(warnUrl, "UTF-8", headerMap);
        if (null != response) {
            if (response.getStatusCode() == 401) {
                accessToken = doLoginRetToken();
                headerMap.put("Authorization", accessToken);
            }
            response = HttpUtils.doGet(warnUrl, "UTF-8", headerMap);
            if (response.getStatusCode() == 200) {
                Map<String, Object> map = gson.fromJson(response.getResponseData(), Map.class);
                Object c = map.get("code");
                List<Warning> warningEntities = null;
                if (c != null) {
                    double code = Double.parseDouble(c.toString());
                    if (code == 1) {
                        Object data = map.get("data");
                        warningEntities = new ArrayList<>();
                        if (null != data) {
                            List<Map<String, Object>> list = (List) data;
                            for (Map<String, Object> m : list) {
                                if (MapUtils.isNotEmpty(m)) {
                                    Warning entity = getWarning(m);
                                    warningEntities.add(entity);
                                }
                            }
                        }
                    } else if (code == 0) {

                    }
                }
                return warningEntities;
            } else {
                log.error(warnUrl + " 调用失败！");
                return null;
            }
        }
        return null;
    }

    /**
     * 将map转为实体
     */
    private Warning getWarning(Map<String, Object> m) {
        Warning entity = new Warning();
        entity.setId(m.get("ID").toString());
        entity.setSpeed(m.get("SPEED") == null ? 0 : (Double) m.get("SPEED"));
        entity.setWarningType(String.valueOf(m.get("WARNINGTYPE")));
        entity.setLocation(String.valueOf(m.get("LOCATION")));
        entity.setLon(String.valueOf(m.get("LON")));
        entity.setContent(String.valueOf(m.get("CONTENT")));
        entity.setLimitSpeed(m.get("LIMITSPEED") == null ? 0 : (Double) m.get("LIMITSPEED"));
        entity.setCarCode(String.valueOf(m.get("CARCODE")));
        entity.setLat(String.valueOf(m.get("LAT")));
        entity.setCjsj(new Date());
        try {
            entity.setWarningTime(m.get("WARNINGTIME") == null ? null
                    : DateUtils.parseDate(m.get("WARNINGTIME").toString(), "yyyy-MM-dd HH:mm:ss"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return entity;
    }


}
